package p2p.tracker.message;

import java.io.IOException;
import java.util.Arrays;

import p2p.tracker.Tracker;
import p2p.tracker.client.ClientManager;
import p2p.utils.Utils;

public class MessageHandler implements Runnable, MessageListener {

	private Message message;
	private Tracker tracker;

	public MessageHandler(Tracker tracker, Message request) {

		this.message = request;
		this.tracker = tracker;

		ClientManager.getInstance().addListener(request.getUuid(), this);

	}

	@Override
	public void run() {

		this.tracker.getListener().logEvent("MessageHandler is executing");

		message.execute();

	}

	@Override
	public void finishedMessageExecution() {
		this.response();
		
		this.tracker.getListener().logEvent(
				"Messagehandler has finished message execution");
	}

	public void response() {

		try {

			this.tracker.getListener().logEvent(
					"Messagehandler is writing respone: "
							+ this.message.getUuid().toString());

			byte[] uuidArray = Utils.uuidToByteArray(this.message.getUuid());

			byte[] responseData = Arrays.copyOf(uuidArray, 18);

			responseData[17] = (byte) 1;

			Tracker.getInstance().sendResponse(responseData,
					this.message.getRequestAddress(),
					this.message.getClientPort());

			this.tracker.getListener().logEvent("------------------------------------");					
			this.tracker.getListener().logEvent(
					"Messagehandler is writing respone on PORT: "
							+ this.message.getClientPort());
			this.tracker.getListener().logEvent("------------------------------------");			

		} catch (IOException e) {

			e.printStackTrace();

		}

	}

}
